package com.inews.base.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.PortResolver;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.GenericFilterBean;

import com.inews.base.utils.InewsUtils;

@Service("sessionTimeoutFilter")
public class SessionTimeOutFilter extends GenericFilterBean {

	@Autowired
	private PortResolver portResolver;
	@Value(value = "/sessionExpired")
	private String sessionTimeOutUrl;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		if (isSessionExpired(httpRequest)) {
			this.processRequest(httpRequest, httpResponse);
		} else {
			chain.doFilter(request, response);
		}
	}

	
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, portResolver);
		session.setAttribute("SPRING_SECURITY_LAST_EXCEPTION", new Exception());
		session.setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", savedRequest);
		String targetUrl = request.getContextPath() + sessionTimeOutUrl;
		response.sendRedirect(response.encodeRedirectURL(targetUrl));
	}

	
	private boolean isSessionExpired(HttpServletRequest request) {
		boolean result = ((InewsUtils.isNotEmpty(request.getRequestedSessionId())) && (!request.isRequestedSessionIdValid()));
		return result; 
	}

	
}
